/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.dromara.cloudeon.controller;


import cn.dev33.satoken.stp.StpUtil;
import org.dromara.cloudeon.dao.UserRepository;
import org.dromara.cloudeon.dto.ResultDTO;
import org.dromara.cloudeon.entity.UserEntity;
import org.dromara.cloudeon.utils.PasswordUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("/change")
public class ChangePasswordController {
    @Resource
    private UserRepository userRepository;

    @RequestMapping("/password")
    private ResultDTO<String> Change(String oldPwd, String newPwd){

        //获取当前用户
        String username="admin";
        String userId = StpUtil.getLoginIdAsString();
        //查询id类型不匹配
        //UserEntity user = userRepository.findById(userId);
        UserEntity user=userRepository.findByUsername(username);


        //检查旧密码是否匹配
        boolean validate = PasswordUtil.validate(oldPwd, user.getPassword());
        if(!validate){
            //旧密码不匹配
            return ResultDTO.failed("旧密码输入错误");
        }

        //旧密码匹配，修改密码
        String digestHex = PasswordUtil.encode(newPwd);
        user.setPassword(digestHex);
        userRepository.save(user);



        //登出
        StpUtil.logout();
        return ResultDTO.success("修改密码成功,请重新登录");
    }


}